package org.erp.common.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
 * 自动填充（创建时间、创建人、更新时间、更新人）配置类
 *
 * @author
 */
@Configuration
public class MybatisPlusAutoFillConfig implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        final String createBy = "createBy";
        boolean createByFlag = metaObject.hasGetter(createBy);
        if (createByFlag) {
            Object createByObject = metaObject.getValue(createBy);
            this.setFieldValByName(createBy, !ObjectUtils.isEmpty(createByObject) ? String.valueOf(createByObject) : "", metaObject);
        }
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        final String updateBy = "updateBy";
        boolean updateByFlag = metaObject.hasGetter(updateBy);
        if (updateByFlag) {
            Object updateByObject = metaObject.getValue(updateBy);
            this.setFieldValByName(updateBy, !ObjectUtils.isEmpty(updateByObject) ? String.valueOf(updateByObject) : "", metaObject);
        }
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
    }

}
